package edu.ynu.se.xiecheng.achitectureclass.common.interceptors;

import edu.ynu.se.xiecheng.achitectureclass.common.utils.JwtUtil;
import edu.ynu.se.xiecheng.achitectureclass.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取令牌
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(401); // 未授权
            return false;
        }
        try {
            // 验证token并提取数据
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 将业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true; // 放行
        } catch (Exception e) {
            response.setStatus(401); // 未授权
            return false; // 不放行
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal
        ThreadLocalUtil.remove();
    }
}
